<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>下发号码</title>
    <link rel="stylesheet" href="../utils/bootstrap-5.3.3-dist/css/bootstrap.min.css">
    <script src="../utils/bootstrap-5.3.3-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../utils/icon/iconfont.css">
    <link rel="stylesheet" href="../css/shared.css">
    <style>
        /*中部布局*/
        .central-layout {
            display: grid;
            grid-template-rows: 70px 470px 50px;
            width: 80vw;
            margin: 0 auto;
        }

        /*
        中部头部布局
         */
        .central-head {
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 10px;
            padding: 5px;
        }

        /*
        表项限宽
        */
        .table td {
            max-width: 15vw;
        }
    </style>
</head>
<body>
<div class="body-grid">
    <!--头部-->
    <div class="header-grid">
        <!--    返回按钮-->
        <div>
            <button class="btn btn-secondary iconfont go-back-button" onclick="window.location.href='athlete.html';">
                &#xe623;
            </button>
        </div>
        <!--    标题-->
        <div class="page-title" id="page-title">
            <script>
                document.getElementById("page-title").innerText=window.sessionStorage.getItem("competitionName")
                +"--下发号码"
            </script>
        </div>
        <div></div>
    </div>
    <!--中部-->
    <div class="central-layout">
        <div class="central-head">
            <!--                搜索框组件-->
            <div style="width: 500px;margin: auto">
                <div class="input-group">
                    <input id="search-input" type="text" class="form-control" placeholder="可按选手姓名、单位名称、组别和选手号码搜索 . . .">
                    <button class="btn btn-outline-secondary iconfont" type="button" onclick="showSearch()">&#xe60a;
                    </button>
                </div>
            </div>
            <button class="btn btn-primary" onclick="oneClickNumber()" id="btn-number-pop">
                一键下发
            </button>
            <button class="btn btn-primary" onclick="downloadNumbers()">
                导出选手号码表
            </button>
        </div>
        <div class="table-responsive">
            <table id="number-table" class="table table-sm table-bordered text-center">
                <thead>
                <tr>
                    <th>选手号码</th>
                    <th>姓名</th>
                    <th>组别</th>
                    <th>性别</th>
                    <th>参赛单位</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="number-tbody" class="table-group-divider">
                </tbody>
            </table>
        </div>
        <div>
            <!--    分页组件-->
            <ul class="pagination page-ul-flex" id="pagination">
            </ul>
        </div>
    </div>
    <!--尾部-->
    <div class="footer-grid">
        <!--网格留空-->
        <div></div>
        <!--进度条-->
        <div id="progress-bar" class="progress-bar-flex">
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增赛事</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增项目</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">设置组别</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">导入选手</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">下发号码</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">制卡</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">签到</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">批次管理</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">规则设置</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">开始比赛</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">成绩计算</div>
                <i class="iconfont progress-bar-arrow" style="visibility: hidden;">&#xe604;</i>
            </div>
        </div>
        <!--   下一步-->
        <div>
            <button class="btn btn-primary iconfont next-button"
                    onclick="nextProgress(CARD_ISSUANCE_PROGRESS,'card-issuance.html')" id="btn-progress">&#xe65b; 
            </button>
        </div>
    </div>
</div>
<!--编辑弹窗-->
<div id="edit-number-dialog" class="my-dialog my-dialog-smaller" style="display: none">
    <div class="my-dialog-header">
        <!--                    标题占位-->
        <span>编辑号码</span>
        <button type="button" class="btn-close close-icon"
                onclick="closeEditNumberDialog()"></button>
    </div>
    <div class="my-dialog-body">
        <div class="input-layout">
            <div class="label-area">
                姓名：
            </div>
            <div class="input-area">

            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                组别：
            </div>
            <div class="input-area">

            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                性别：
            </div>
            <div class="input-area">

            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                单位：
            </div>
            <div class="input-area">

            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                <label for="number">选手号码<span style="color:red;">*</span>：</label>
            </div>
            <div class="input-area">
                <input type="text" id="number" style="width: 100%">
            </div>
            <div class="err-area">
                <small id="number-err" style="color: red;"></small>
            </div>
        </div>
    </div>
    <div class="my-dialog-footer">
        <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                onclick="closeEditNumberDialog()">取消
        </button>
        <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                onclick="submitEditDialog()">确认
        </button>
    </div>
</div>
<script src="../js/pages.js"></script>
<script src="../api/urls.js"></script>
<script src="../js/dialog.js"></script>
<script src="../js/progress.js"></script>
<script src="../js/request.js"></script>
<script>
    updateProgress("progress-bar", NUMBER_PROGRESS);
    //页码
    let pageNum = 1;
    //一页多少条
    let pageSize = 9;
    //总条数
    let total;
    //总页数
    let pages;
    //请求记录
    let records;
    //更新id
    let updateId;
    //搜索内容
    let searchAll;

    /**
     * 打开编辑弹窗
     */
    function openEditNumberDialog(record){
        let inputAreas = document.querySelectorAll("#edit-number-dialog .input-area");
        inputAreas[0].textContent=record.name;
        inputAreas[1].textContent=record.group;
        inputAreas[2].textContent=record.gender;
        inputAreas[3].textContent=record.unit;
        inputAreas[4].firstElementChild.value=record.number;
        openDialog("edit-number-dialog");
    }

    /**
     * 关闭编辑弹窗
     */
    function closeEditNumberDialog(){
        let inputAreas = document.querySelectorAll("#edit-number-dialog .input-area");
        inputAreas[0].textContent=null;
        inputAreas[1].textContent=null;
        inputAreas[2].textContent=null;
        inputAreas[3].textContent=null;
        inputAreas[4].firstElementChild.value=null;
        let errs = document.querySelectorAll("#edit-number-dialog small");
        for (let err of errs) {
            err.textContent=null;
        }
        closeDialog("edit-number-dialog");
    }

    /**
     * 校验选手号码
     */
    async function validateNumber(){
        let numberInput = document.getElementById("number");
        let err = document.getElementById("number-err");
        let flag=true;
        if(numberInput.value.length>30){
            err.textContent="不能超过30个字！";
            flag=false;
        }
        if(numberInput.value.trim().length===0){
            err.textContent="不能为空！";
            flag=false;
        }
        let url = new URL(NUMBER_URL+"/check");
        url.searchParams.set("competitionId",window.sessionStorage.getItem("competitionId"));
        url.searchParams.set("number",numberInput.value);
        url.searchParams.set("numberId",updateId);
        await fetch(url).then(resp=>{return resp.text()}).then(result=>{
            if(result==="no"){
                err.textContent="号码不能重复！";
                flag=false;
            }
        });
        return flag;
    }

    /**
     * 提交编辑弹窗
     */
    async function submitEditDialog(){
        let errs = document.querySelectorAll("#edit-number-dialog small");
        for (let err of errs) {
            err.textContent=null;
        }
        if(!await validateNumber()){
            return;
        }
        let bodyObject={};
        bodyObject.id=updateId;
        bodyObject.number=document.getElementById("number").value.trim();
        await fetch(NUMBER_URL+UPDATE_URL,{
            method:"POST",
            headers: new Headers({"Content-Type": "application/json"}),
            body: JSON.stringify(bodyObject)
        });
        closeEditNumberDialog();
        await showSearch();
    }

    /**
     * 一键下发
     */
    async function oneClickNumber() {
        let url = new URL(NUMBER_URL + "/oneClick");
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        await fetch(url, {
            method: "POST"
        });
        await showSearch();
    }

    /**
     * 下载号码表
     */
    async function downloadNumbers() {
        let url1 = new URL(NUMBER_URL + "/download");
        url1.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        await fetch(url1).then(resp => {
            return resp.blob();
        }).then(blob => {
            // 创建一个指向 Blob 的 URL
            const url = window.URL.createObjectURL(blob);

            // 创建 <a> 元素
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = '选手号码表.xlsx'; // 设置下载的文件名

            // 添加 <a> 到文档中，并触发点击事件
            document.body.appendChild(a);
            a.click();

            // 清理资源
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        });
    }

    /**
     * 点击搜索
     */
    async function showSearch() {
        pageNum = 1;
        await showPage();
    }

    /**
     * 渲染表格
     */
    function drawNumberTable(records) {
        let tableBody = document.getElementById("number-tbody");
        tableBody.innerHTML = "";
        for (let record of records) {
            let trElement = document.createElement("tr");
            trElement.dataset.numberId = record.id;
            let tdElement1 = document.createElement("td");
            tdElement1.textContent = record.number;
            let tdElement2 = document.createElement("td");
            tdElement2.textContent = record.name;
            let tdElement3 = document.createElement("td");
            tdElement3.textContent = record.group;
            let tdElement4 = document.createElement("td");
            tdElement4.textContent = record.gender;
            let tdElement5 = document.createElement("td");
            tdElement5.textContent = record.unit;
            let tdElement11 = document.createElement("td");
            let buttonElement1 = document.createElement("button");
            buttonElement1.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
            buttonElement1.textContent = "\u{e6f7}编辑";
            buttonElement1.addEventListener("click",() => {
                updateId = record.id;
                openEditNumberDialog(record);
            });
            tdElement11.append(buttonElement1);
            trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5, tdElement11);
            tableBody.append(trElement);
        }
    }

    //实现分页的方法
    async function getPage(pageNum, pageSize) {
        let searchInput = document.getElementById("search-input");
        searchAll = searchInput.value;
        let url = new URL(NUMBER_URL + "/searchAll");
        url.searchParams.set("pageNum", pageNum);
        url.searchParams.set("pageSize", pageSize);
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        url.searchParams.set("searchAll", searchAll);
        await fetch(url).then(response => {
            if (response.ok && response.headers.get("Content-Type") === "application/json") {
                return response.json();
            } else {
                throw new Error(`未知相应状态 ${response.status}或Content-Type：${response.headers.get("Content-Type")}`);
            }
        }).then(async pageInfo =>  {
            pages = pageInfo.pages;
            total = pageInfo.total;
            records = pageInfo.records;
            console.log(records)
            //发送请求，判断是否存在空的号码
            let url = new URL(NUMBER_URL+'/containEmpty')
            url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"))
            let res = await fetch_http({
                url: url,
                method: 'get'
            })
            console.log(res)
            if(res.code == 200 && res.data){
                document.getElementById("btn-progress").disabled=true;
            }else{
                document.getElementById("btn-progress").disabled=false;

            }


            drawNumberTable(records);
        }).catch(error => {
            console.log("分页错误：", error);
        });

    }

    //上一页
    async function prePage() {
        pageNum = pageNum - 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    //下一页
    async function nextPage() {
        pageNum = pageNum + 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages)
    }

    //点击切换
    async function handlePage(page) {
        if (page !== pageNum) {
            pageNum = page
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

    }

    /**
     * 改变每页条数
     */
    async function changePageSize(value) {
        pageSize = Number(value);
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    // 创建分页组件
    async function showPage() {
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);

        let url=new URL(PROJECT_URL + "/getEarliestProject");
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        let res = await fetch_http({
            url:url,
            method:'GET'
        })
        if(res.code == 200 && new Date().getTime() > new Date(res.data.startTime).getTime()){  //如果当前时间超过第一个项目的开始时间 该按钮禁用
            let batchSign=document.getElementById("btn-number-pop")
            batchSign.disabled = true;
        }

    }

    if (window.sessionStorage.getItem("competitionId")) {
        (async () => {
            await showPage();
        })();
    }


</script>
</body>
</html>